package com.weimob.mcloud.wechatwork.customer.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.common.collect.Lists;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.OrgDepartmentUserExport;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.data.EmployeeBO;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.req.EmployeeDTO;
import com.weimob.mcloud.wechatwork.core.adapter.enums.cdp.CDPMarkTypeEnum;
import com.weimob.mcloud.wechatwork.core.adapter.enums.cdp.CdpMarkMessageEventEnum;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.cdp.request.customer.CDPUserMarkDTO;
import com.weimob.mcloud.wechatwork.core.adapter.service.OneCrmAdapterService;
import com.weimob.mcloud.wechatwork.core.adapter.service.cdp.CdpUserAdapterService;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.enums.group.GroupMemberTypeEnum;
import com.weimob.mcloud.wechatwork.core.service.group.request.CustomerGroupCreateRequest;
import com.weimob.mcloud.wechatwork.core.service.group.request.CustomerGroupMemberDTO;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.customer.listener.enums.CustomerGroupMemberCDPMarkTypeEnum;
import com.weimob.mcloud.wechatwork.customer.listener.event.CustomerGroupMemberEvent;
import com.weimob.mcloud.wechatwork.customer.third.customer.CustomerThird;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author liuzhu.chen
 * @Description
 * @Date 2021/11/12 15:34
 */
@Component
@Slf4j
public class CustomerGroupMemberCDPMarkListener {
    @Reference
    private PrivateSphereService privateSphereService;

    @Reference
    private OneCrmAdapterService oneCrmAdapterService;

    @Reference
    private CdpUserAdapterService cdpUserAdapterService;

    @Reference
    OrgDepartmentUserExport orgDepartmentUserExport;

    @Autowired
    private CustomerThird customerThird;

    /**
     * 企微助手产品id
     */
    @Value("${aewc.productId:203}")
    private Long aewcProductId;

    /**
     * 客户进群/退群事件 CDP打点
     *
     * @param customerGroupMemberEvent
     */
    @Async("groupSyncCDPPointThreadPool")
    @EventListener
    public void customerGroupMemberCDPMarkListener(CustomerGroupMemberEvent customerGroupMemberEvent) {
        if (Objects.isNull(customerGroupMemberEvent)) {
            return;
        }

        CustomerGroupCreateRequest customerGroupDTO = customerGroupMemberEvent.getCustomerGroupDTO();
        List<CustomerGroupMemberDTO> groupMemberList = customerGroupMemberEvent.getCustomerGroupMemberDTOList();
        Integer operateType = customerGroupMemberEvent.getOperateType();
        PrivateSphere privateSphere = customerGroupMemberEvent.getPrivateSphere();

        if (Objects.isNull(customerGroupDTO) || CollectionUtils.isEmpty(groupMemberList)) {
            log.warn("客户进群/退群CDP打点事件,customerGroupDTO客户群信息为null OR groupMemberList客户群成员信息为null");
            return;
        }

        for (CustomerGroupMemberDTO groupMember : groupMemberList) {
            if (GroupMemberTypeEnum.EMPLOYEE.getCode().equals(groupMember.getType())) {
                continue;
            }
            // 查询主客户wid
            Long superWid = customerThird.getSuperWid(privateSphere.getBosId(), groupMember.getMemberId(), privateSphere.getCorpId());
            if (Objects.isNull(superWid)) {
                log.warn("客户进群/退群CDP打点事件,获取wid失败,corpId:{},memberId:{}", groupMember.getCorpId(), groupMember.getMemberId());
                return;
            }
            // CDP打点 进群/退群事件
            CDPUserMarkDTO cdpUserMarkDTO = getCdpUserMarkDTO(customerGroupDTO, operateType, privateSphere, groupMember, superWid);
            cdpUserAdapterService.markCDPUserMsg(cdpUserMarkDTO);
            log.info("客户进群/退群CDP打点事件,成功,message:{}", cdpUserMarkDTO);
        }
    }

    /**
     * convert
     *
     * @param customerGroupDTO
     * @param operateType
     * @param privateSphere
     * @param groupMember
     * @param superWid
     * @return
     */
    private CDPUserMarkDTO getCdpUserMarkDTO(CustomerGroupCreateRequest customerGroupDTO, Integer operateType, PrivateSphere privateSphere, CustomerGroupMemberDTO groupMember, Long superWid) {
        CDPUserMarkDTO cdpUserMarkDTO = new CDPUserMarkDTO();
        cdpUserMarkDTO.setuKey(String.valueOf(superWid));
        cdpUserMarkDTO.setuKeyType("wid");
        cdpUserMarkDTO.setsChannelType(203);
        cdpUserMarkDTO.setsChannelId(privateSphere.getProductInstanceId());
        cdpUserMarkDTO.setBosId(privateSphere.getBosId());
        long currentTimestamp = System.currentTimeMillis();
        cdpUserMarkDTO.setUpdateTime(String.valueOf(currentTimestamp));
        Map<String, Object> dataJson = new HashMap<>(16);
        dataJson.put("productInstanceId", privateSphere.getProductInstanceId());
        dataJson.put("wid", String.valueOf(superWid));
        dataJson.put("externalUserId", groupMember.getMemberId());
        dataJson.put("corpId", groupMember.getCorpId());
        dataJson.put("timestamp", currentTimestamp);
        dataJson.put("groupId", groupMember.getGroupId());
        if (StringUtils.isEmpty(customerGroupDTO.getName())) {
            dataJson.put("groupName", getGroupName(customerGroupDTO,privateSphere));
        } else {
            dataJson.put("groupName", customerGroupDTO.getName());
        }
        dataJson.put("join_group_way", groupMember.getJoinScene());
        dataJson.put("quit_group_way", groupMember.getQuitScene());
        cdpUserMarkDTO.setDataJson(dataJson);
        cdpUserMarkDTO.setCdpMarkTypeEnum(CDPMarkTypeEnum.CDP_USER_ACTION);
        // 客户进群/退群事件
        if (CustomerGroupMemberCDPMarkTypeEnum.JOIN_GROUP.getCode().equals(operateType)) {
            cdpUserMarkDTO.setCdpMarkMessageEventEnum(CdpMarkMessageEventEnum.JOIN_GROUP);
        } else if (CustomerGroupMemberCDPMarkTypeEnum.QUIT_GROUP.getCode().equals(operateType)) {
            cdpUserMarkDTO.setCdpMarkMessageEventEnum(CdpMarkMessageEventEnum.QUIT_GROUP);
        }
        return cdpUserMarkDTO;
    }

    private String getGroupName(CustomerGroupCreateRequest customerGroupDTO, PrivateSphere privateSphere) {
        EmployeeDTO employeeDTO = new EmployeeDTO();
        employeeDTO.setCorpId(customerGroupDTO.getCorpId());
        employeeDTO.setBosId(privateSphere.getBosId());
        employeeDTO.setUserIds(Lists.newArrayList(customerGroupDTO.getOwner()));
        SoaResponse<List<EmployeeBO>, ?> usersByUserIds = orgDepartmentUserExport.getUsersByUserIds(employeeDTO);
        List<EmployeeBO> employeeBOList = SoaUtil.unpack(usersByUserIds);
        if (CollectionUtils.isNotEmpty(employeeBOList)) {
            return String.format("%s的群（未命名）", employeeBOList.get(0).getName());
        }
        return "";
    }


}
